package com.frame.pageform.tag;

import java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
import com.frame.pageform.PageOgnlContext;
import com.frame.pageform.RequestContext;

abstract public class BaseTag extends TagSupport{

   protected PageOgnlContext pageOgnlContext;

   public BaseTag()
   {
   }

   final public int doStartTag() throws JspException
   {
      try
      {
         RequestContext context = RequestContext.getContext();

         if(context != null)
         {
            pageOgnlContext = getContext().getPageOgnlContext();
         }

         return start();
      }
      catch (Exception ex)
      {
         if (ex instanceof JspException)
            throw (JspException) ex;
         else if (ex instanceof RuntimeException)
            throw (RuntimeException) ex;
         else
            throw new JspException(ex);
      }
   }

   final public int doEndTag() throws JspException
   {
      try
      {
         return end();
      }
      catch (Exception ex)
      {
         if (ex instanceof JspException)
            throw (JspException) ex;
         else if (ex instanceof RuntimeException)
            throw (RuntimeException) ex;
         else
            throw new JspException(ex);
      }
   }

   final public int doAfterBody() throws JspException
   {
      try
      {
         return afterBody();
      }
      catch (Exception ex)
      {
         if (ex instanceof JspException)
            throw (JspException) ex;
         else if (ex instanceof RuntimeException)
            throw (RuntimeException) ex;
         else
            throw new JspException(ex);
      }
   }

   abstract public int start() throws Exception;

   public int end() throws Exception
   {
      return 0;
   }

   public int afterBody() throws Exception
   {
      return 0;
   }

   /**
    * 获得表达式的值
    * @param expression
    * @return
    * @throws Exception
    * @throws PageException
    */
   protected Object executeExpression(String expression) throws Exception
   {
      if(getContext()!=null)
         return getContext().executeExpression(expression);
      else return null;
   }

   /**
    * 输出数据
    * @param obj
    * @throws IOException
    */
   final protected void write(String s) throws IOException
   {
      JspWriter writer = pageContext.getOut();
      writer.write(s);
   }

   final protected void writeln(String s) throws IOException
   {
      write(s + "\n");
   }

   /**
    * 设置变量
    * @param name
    * @param value
    */
   final protected void setVariable(String name, Object value)
   {
      pageContext.setAttribute(name, value);
      pageOgnlContext.setVariable(name, value);
   }
   protected RequestContext getContext()
   {
      return RequestContext.getContext();
   }
}
